package com.kaifamiao.jdbc.transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 事务处理三步骤:
 *      1、关闭自动提交
 *      2、在同一个事务中执行多个DML时，若都执行成功则提交事务，但凡有一个失败即可回滚整个事务
 *      3、启用自动提交
 * 在JDBC程序中 Connection 的事务提交模式默认就是 自动提交，即每执行一个DML语句就会自动提交事务
 */
public class TransactionHandling {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        String driverClassName = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/kaifamiao?serverTimezone=Asia/Chongqing";
        String username = "kfm";
        String password = "kfm";

        /*
        String driverClassName = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:kaifamiao";
        String username = "kaifamiao";
        String password = "kaifamiao";
        */

        Class.forName( driverClassName );
        Connection conn = DriverManager.getConnection( url, username, password );
        System.out.println( "autocommit: " + conn.getAutoCommit() );

        // 关闭事务自动提交
        conn.setAutoCommit( false );

        Statement stmt = conn.createStatement();

        try {
            // 在同一个事务中执行多个DML操作
            stmt.executeUpdate( "INSERT INTO t_pandas (name) VALUES ( '小然' )" );
            stmt.executeUpdate( "DELETE FROM t_pandas WHERE  name = '大美'" );
            // 手动提交事务
            conn.commit();
        } catch ( SQLException cause ) {
            // 手动回滚事务
            conn.rollback();
        }

        // 启用事务自动提交
        conn.setAutoCommit( true );

        // 以下DML语句执行后事务会自动提交
        stmt.executeUpdate( "DELETE FROM t_pandas WHERE  name = '大熊猫儿'" );

        stmt.close();
        conn.close();
    }

}
